<script  setup>
import {onMounted, ref} from "vue";
import {
  selectOrder,
  addOrder,
  selectOrderById,
  updateOrder,
  approvalOrder,
  updateOrderStatus,
  deleteOrder,
  deleteCustomer
} from "@/api/sale.js";
import { useRouter } from 'vue-router';
import {ElMessage, ElMessageBox} from 'element-plus'


//自定义的响应式数组
const tableData =ref([])
//页数
const size = ref('default')
const background = ref(false)
//定义是否为编辑状态的响应式变量
const disabled = ref(false)
// 定义对话框是否显示的响应式变量
const Isdisable = ref(false)
//当前页
const PageNum = ref(1)
//每页显示条数
const PageSize = ref(5)
//总条数
const total = ref(null)
//管理表单提交状态
const submitting = ref(false)






// 审批弹窗显示状态
const approveDialogVisible = ref(false);
// 审批表单数据
const approveForm = ref({
  approvalStatus: '',
  comment: ''
});
// 选中的订单行
const currentRow = ref(null);

// 审批按钮点击事件
const approval = async (row) => {
  currentRow.value = row;
  approveDialogVisible.value = true;
};
// 处理审批提交
const handleApprove = async () => {
  if (!approveForm.value.approvalStatus) {
    ElMessage.error('请选择审批状态');
    return;
  }
  const res = await approvalOrder(
        currentRow.value.id,
        approveForm.value.approvalStatus,
        approveForm.value.comment
  );
  ElMessage.success(res.data.msg);
  approveDialogVisible.value = false;
  await selectl()
  // 添加条件判断
  if (res.data.msg === "修改订单状态成功，已通过审核") {
    await updateOrderStatus(currentRow.value) // 替换 anotherMethod 为实际要执行的方法名
  }
  await selectl()
};





//输入框绑定的响应式变量
const orId = ref("")//订单id
const cuid = ref("")//客户id
const maTid = ref("")//商品id
//当每页条数发生了变化，调用此函数
const handleSizeChange = (size) => {
   PageSize.value = size
   PageNum.value=1
   selectl()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  PageNum.value = num
  selectl()
}
//查询按钮
const selectl=async()=>{

    const response = await selectOrder(
        cuid.value,
        orId.value,
        maTid.value,
        PageNum.value,
        PageSize.value)
    console.log(response)
    //分页条件数据模型
    tableData.value = response.data.data.rows
    total.value = response.data.data.total
}

onMounted(()=>{
  selectl()
})



//重置表单
const resetForm = () => {
  Order.value={
    id:'',//订单id
    orderDate:'',//客户下达订单的具体日期
    cuid:'',//客户id
    orderQuantity:'',//客户订购的零件数量
    maTid:'',//客户订购的零件id
    deliveryDate:'',//客户要求交付订单的具体日期
    contactAddress:'',//客户发货地址
    receivedAmount:'否',//客户是否收款
    shipmentStatus:'',//订单发货状态
    approvalStatus:'待审批',//订单是否通过审批,待审批, 已通过, 已拒绝
    comment:''//批注
  }
 Isdisable.value=false
}




//定义一个订单对象
const Order = ref({
  id:'',//订单id
  orderDate:'',//客户下达订单的具体日期
  cuid:'',//客户id
  orderQuantity:'',//客户订购的零件数量
  maTid:'',//客户订购的零件id
  deliveryDate:'',//客户要求交付订单的具体日期
  contactAddress:'',//客户发货地址
  receivedAmount:'否',//客户是否收款
  shipmentStatus:'',//订单发货状态
  approvalStatus:'待审批',//订单是否通过审批,待审批, 已通过, 已拒绝
  comment:''//批注
})


//点击跳转添加按钮
const goToadd=()=> {
  //false表示可以添加
  disabled.value = false
  //清空表单
  resetForm()
  //显示对话框
  Isdisable.value = true
}



//创建对象，存取修改所用的对象内容(修改表单)
const updateI=(row)=>{
  console.log(row)
  //显示对话框
  Isdisable.value = true
  //true表示可以添加
  disabled.value = true
  //将修改的数据赋值给对象
  Object.assign(Order.value,row)

}
//修改添加函数
const submitForm = async () => {
  //提取日期格式化函数
  const formatDate = (dateStr) => {
    const date = new Date(dateStr);
    const iso = date.toISOString();
    return iso.split('T')[0] + 'T' + iso.split('T')[1].split('.')[0];
  };
  // 格式化日期,重新赋值回原对象
  Order.value.orderDate = formatDate(Order.value.orderDate);
  Order.value.deliveryDate = formatDate(Order.value.deliveryDate);
  if (!disabled.value) {
    const add = await addOrder(Order.value)
    console.log(add)
    ElMessage.success(add.data.msg)
    await selectl()
  }else {
    await selectOrderById(Order.value)
    const update = await updateOrder(Order.value)
    console.log(update)
    ElMessage.success(update.data.msg)
    //清空表单
    Order.value = {}
    //重新查询
    await selectl()
  }
  //关闭对话框
  Isdisable.value = false
}


//删除订单
const del =async (row) => {
  ElMessageBox.confirm(
      '确定要删除数据吗？',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async ()=>{
        const rows=await deleteOrder(row.id)
        ElMessage(rows.data.msg)
        await selectl();
      }
  )
}






//定义验证规则
const rules = {
  orderDate:[
    { required: true, message: '客户下订单的具体日期', trigger: 'blur' },
  ],
  cuid: [
    { required: true, message: '请输入客户id', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
  ],
  orderQuantity: [
    { required: true, message: '客户订购的零件数量', trigger: 'blur' },
    { pattern: /^(\d+(\.\d{2})?)$/, message: '客户订购的零件数量必须为数字', trigger: 'blur' }
  ],
  orderAmount:[
    { required: true, message: '订单的总金额', trigger: 'blur' },
    { pattern: /^(\d+(\.\d{2})?)$/, message: '订单的总金额必须为数字,并且必须为小数点后两位', trigger: 'blur' }
  ],
  maTid: [
    { required: true, message: '请输入客户订购的零件id', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
  ],
  deliveryDate:[
    { required: true, message: '客户要求交付订单的具体日期', trigger: 'blur' },
  ],
  contactAddress:[
    { required: true, message: '请输入客户的发货地址', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  shipmentStatus:[
    { required: true, message: '请输入客户订单的发货状态', trigger: 'blur' }
  ]

}


</script>

<template>

  <el-card>
    <el-row :gutter="20">
      <el-col :span="6" class="sou">
        <el-input
            type="text"
            placeholder="请输入订单id"
            v-model="orId"
            suffix-icon="Search"

        />
      </el-col>

      <el-col :span="6" class="sou">
        <el-input
            type="text"
            placeholder="请输入客户id"
            v-model="cuid"
            suffix-icon="Search"
        />
      </el-col>

      <el-col :span="6" class="sou">
        <el-input
            type="text"
            placeholder="请输入商品id"
            v-model="maTid"
            suffix-icon="Search"
        />
      </el-col>

      <el-button type="primary" @click="selectl()">搜索</el-button>

      <el-button type="primary" @click="goToadd()">添加订单</el-button>

    </el-row>

    <el-table :data="tableData" style="width: 100%">

      <el-table-column fixed prop="id" label="订单号" width="120" />
      <el-table-column prop="customerName" label="客户名称" width="120" />
      <el-table-column prop="name" label="商品名称" width="160" />
      <el-table-column prop="orderDate" label="客户下单日期" width="160" />
      <el-table-column prop="orderQuantity" label="商品数量" width="120" />
      <el-table-column prop="orderAmount" label="总额" width="120" />
      <el-table-column prop="deliveryDate" label="交货日期" width="160" />
      <el-table-column prop="contactAddress" label="收货地址" width="120" />
      <el-table-column prop="shipmentStatus" label="发货状态" width="120" />
      <el-table-column prop="receivedAmount" label="是否收款" width="120" />
      <el-table-column prop="approvalStatus" label="审批" width="120" />
      <el-table-column prop="comment" label="批注" width="120" />


      <el-table-column fixed="right" label="操作" min-width="200">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="del(scope.row)">
            删除
          </el-button>
          <el-button link type="primary" size="small" @click="updateI(scope.row)">
            修改
          </el-button>
          <el-button link type="primary" size="small" @click="approval(scope.row)">
            审批
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <div class="demo-pagination-block">
      <!--分页查询-->
      <el-pagination
          v-model:current-page="PageNum"
          v-model:page-size="PageSize"
          :page-sizes="[3, 5, 10, 15]"
          :size="size"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="onCurrentChange"
      />
    </div>
  </el-card>


<!-- 添加和修改的弹窗-->
  <el-dialog  v-model="Isdisable" :title="disabled ? '编辑订单':'新增订单'" width="30%" align-center>

    <el-form :model="Order" :rules="rules"  ref="formRef" label-width="auto">

      <el-form-item label="订单id" prop="id" v-if="disabled">
        <el-input disabled v-model="Order.id" placeholder="订单id"></el-input>
      </el-form-item>


      <el-form-item label="客户下订单的具体日期" required>
        <el-col :span="11">
          <el-form-item prop="date1">
            <el-date-picker
                v-model="Order.orderDate"
                type="date"
                aria-label="Pick a date"
                placeholder="Pick a date"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col class="text-center" :span="2">
          <span class="text-gray-500">-</span>
        </el-col>
        <el-col :span="11">
          <el-form-item prop="date2">
            <el-time-picker
                v-model="Order.orderDate"
                aria-label="Pick a time"
                placeholder="Pick a time"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-form-item>


      <el-form-item label="客户id" prop="cuid" >
        <el-input  v-model="Order.cuid" placeholder="客户id"></el-input>
      </el-form-item>

      <el-form-item label="客户订购的零件数量" prop="orderQuantity">
        <el-input v-model="Order.orderQuantity" placeholder="客户订购的零件数量"></el-input>
      </el-form-item>


      <el-form-item label="客户订购的零件id" prop="maTid">
        <el-input v-model="Order.maTid" placeholder="客户订购的零件id"></el-input>
      </el-form-item>


      <el-form-item label="客户要求交付订单的具体日期" required>
        <el-col :span="11">
          <el-form-item prop="date1">
            <el-date-picker
                v-model="Order.deliveryDate"
                type="date"
                aria-label="Pick a date"
                placeholder="Pick a date"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col class="text-center" :span="2">
          <span class="text-gray-500">-</span>
        </el-col>
        <el-col :span="11">
          <el-form-item prop="date2">
            <el-time-picker
                v-model="Order.deliveryDate"
                aria-label="Pick a time"
                placeholder="Pick a time"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-form-item>


      <el-form-item label="客户发货地址" prop="contactAddress">
        <el-input v-model="Order.contactAddress" placeholder="客户发货地址"></el-input>
      </el-form-item>


      <el-form-item label="订单发货状态" prop="shipmentStatus">
        <el-select v-model="Order.shipmentStatus" placeholder="订单发货状态">
          <el-option label="未发货" value="未发货" />
          <el-option label="已发货" value="已发货" />
        </el-select>
      </el-form-item>


      <el-form-item label="说明信息" prop="remarks">
        <el-input v-model="Order.comment" type="textarea" />
      </el-form-item>

    </el-form>

    <template  #footer>
      <el-button @click="resetForm()">取消</el-button>
      <el-button type="primary" @click="submitForm"  :loading ="submitting">
        {{ submitting ? '提交中...' :disabled? '保存修改' : '添加' }}
      </el-button>
    </template>

   </el-dialog>

  <!-- 审批弹窗 -->
  <el-dialog
      v-model="approveDialogVisible"
      title="订单审批"
      width="400px"
  >
    <el-form :model="approveForm" label-width="80px">
      <el-form-item label="审批状态">
        <el-select v-model="approveForm.approvalStatus" placeholder="请选择审批状态">
          <el-option label="已通过" value="已通过"></el-option>
          <el-option label="已拒绝" value="已拒绝"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审批意见">
        <el-input
            v-model="approveForm.comment"
            type="textarea"
            placeholder="请输入审批意见"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="approveDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleApprove">确认审批</el-button>
    </template>
  </el-dialog>


  <!--  添加和修改的对话框-->



</template>



<style lang="scss">
*{
  padding: 0;
  margin: 0;
}

html,
body
{
  height: 100%;
}

.border-row {
  border: 1px solid #e4e7ed; /* 边框颜色和宽度 */
  padding: 10px; /* 可选：调整内边距 */
}

.border-col{
  height: 50px;
  border: 1px solid #e4e7ed; /* 边框颜色和宽度 */
  padding: 10px; /* 可选：调整内边距 */
}

.demo-pagination-block{
  height: 100px;
  margin-top: 10px;
  margin-bottom: 16px;
}

//.demo-pagination-block .demonstration {
//  margin-bottom: 16px;
//}



</style>